#include <iostream>
#include <unistd.h>
#include <pthread.h>
using namespace std;

// 共享资源
int cnt = 0;

// 静态初始化互斥锁和条件变量
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void *Count(void *args){
    // 分离线程
    pthread_detach(pthread_self());

    uint64_t number = (uint64_t)args;
    cout << "pthread: " << number << " create success" << endl;

    while(true){
        // 申请锁
        pthread_mutex_lock(&mutex);
        // 等待条件变量
        pthread_cond_wait(&cond, &mutex);

        cout << "pthread: " << number << " , cnt: " << cnt++ << endl;
        // 释放锁
        pthread_mutex_unlock(&mutex);
    }
}

int main(){
    for (uint64_t i = 0; i < 5; i++){
        pthread_t tid;
        pthread_create(&tid, nullptr, Count, (void *)i);
        usleep(10);
    }

    sleep(3);
    cout << "main thread ctrl begin: " << endl;

    while(true){
        sleep(1);
        // 唤醒一个等待的线程
        pthread_cond_signal(&cond);
        cout << "signal one thread..." << endl;

        // 唤醒所有等待的线程
        // pthread_cond_broadcast(&cond);
        // cout << "broadcast all thread..." << endl;
    }

    return 0;
}